package com.hzjh.h5mall.ui.web

import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.hzjh.base.ext.data.FlowConst
import com.hzjh.base.ext.frame.JHBaseActivity
import com.hzjh.base.ext.route.RouteUrl
import com.hzjh.base.frame.BaseViewModel
import com.hzjh.base.log.JHLogger
import com.hzjh.base.utils.eventbus.FlowBus
import com.hzjh.base.utils.other.CheckUtils
import com.hzjh.base.web.core.JHWebView
import com.hzjh.base.web.util.AndroidBug5497Workaround
import com.hzjh.base.web.util.JHWebViewPool

abstract  class JHBaseWebActivity<T : ViewBinding, VM : BaseViewModel> :JHBaseActivity<T,VM>(), JHWebView.OnWebChangeListener{
    @JvmField
    @Autowired(name = RouteUrl.PARAMS_WEB_URL)
    var mWebUrl: String = ""

    val mWebView by lazy { JHWebViewPool.getInstance().getWebView(this,mWebUrl) }
    private val jsBridge by lazy { JSBridge(mWebView) }
    private val flContent by lazy { getWebFlContent() }
    override fun initData() {
        if(CheckUtils.isEmpty(mWebUrl)){
            mWebUrl=intent.getStringExtra(RouteUrl.PARAMS_WEB_URL)?:""
        }
        JHLogger.d("当前加载H5地址----$mWebUrl")
    }

    override fun initView() {
        val params = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        flContent.addView(mWebView,params)
        mWebView.setLifecycleOwner(this)
        mWebView.setOnWebChangeListener(this)
        mWebView.addJsBridge(jsBridge)

        mWebView.guangLoadUrl(mWebUrl,true)
        //webView软键盘挡住输入框 会导致页面展示内容不完全
        AndroidBug5497Workaround.assistActivity(flContent,this)
    }

    override fun initObservable() {
        super.initObservable()
        //监听登录状态回调
        FlowBus.with<Boolean>(FlowConst.REFRESH_LOGIN_STATUS).register(this) {
            jsBridge.appLoginResult(mWebView,if(it) 1 else 0)
        }
        //监听广告状态同步
        FlowBus.with<Boolean>(FlowConst.REFRESH_ADS_STATUS).register(this) {
            jsBridge.adsStatusChange(mWebView)
        }
    }

    override fun titleChange(title: String?) {
    }

    override fun progressChange(progress: Int) {
    }

    override fun onInnerLinkChecked(url: String?) {
        JHLogger.d("跳转加载H5地址----$url")
    }

    override fun onWebLoadError() {
    }

    override fun onWebLoadStart(url: String) {
    }

    override fun onWebLoadFinish(url: String?) {
    }

    override fun onWebLoadStatus(params: Map<String, String>) {
    }

    override fun showLoadingAnim(show: Boolean?) {
        //不显示loading
//        if(show == true) LoadingDialogManager.get().showLoading(ActivityStackManage.currentActivity())
//        else LoadingDialogManager.get().dismissLoading()
    }

    abstract fun getWebFlContent():FrameLayout
}